package cc.autoapi.pucong.auto.flow.core.root.utils;

import cc.autoapi.pucong.auto.flow.core.root.exception.AutoFlowException;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.CronExpression;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * cron表达式工具类
 */
@Slf4j
public class CronUtil {

    /**
     * 校验表达式是否可用
     *
     * @param cron
     * @return
     */
    public static Boolean checkCron(String cron) {
        return CronExpression.isValidExpression(cron);
    }

    /**
     * 获取下一次执行日期
     *
     * @return
     */
    public static Date getNextExecDate(String cron) {
        Date nextDate = getNextExecDate(cron, new Date());
        return nextDate;
    }

    public static Date getNextExecDate(String cron, Date time) {
        Date nextDate = null;
        if (!checkCron(cron)) {
            throw new AutoFlowException("cron表达式格式不正确！");
        }
        try {
            CronExpression cronExpression = new CronExpression(cron);
            nextDate = cronExpression.getNextValidTimeAfter(time);
        } catch (ParseException e) {
            throw new AutoFlowException("cron表达式解析异常:" + e.getMessage());
        }
        return nextDate;
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date nextExecDate = getNextExecDate("0 23/5 * * * ? *");
        System.out.println(sdf.format(nextExecDate));
    }
}
